// Item同步到旺店通功能 - 只添加同步按钮，不覆盖现有功能

// 直接设置listview_settings
frappe.listview_settings["Item"] = frappe.listview_settings["Item"] || {};

// 添加onload函数
frappe.listview_settings["Item"].onload = function(listview) {
    listview.page.sidebar.toggle(false);
    // Add "Sync to WDT" menu item
    listview.page.add_menu_item(__("Sync to WDT"), function() {
        sync_items_to_wdt(listview);
    });
    
    // 添加查询库存按钮到菜单
    listview.page.add_menu_item(__("Query Inventory"), function() {
        query_items_inventory(listview);
    });

    // 添加 WDT + Shopify 库存查询按钮到菜单
    listview.page.add_menu_item(__("Query WDT & Shopify Inventory"), function() {
        query_items_inventory_with_shopify(listview);
    });
    
    // 添加查询库位按钮到菜单
    listview.page.add_menu_item(__("Query Bin Positions"), function() {
        query_all_positions();
    });

    // Shopify SKU 直接导入到 ERPNext 按钮
    listview.page.add_menu_item(__("从Shopify导入商品"), function() {
        open_shopify_import_dialog();
    });
    
    // Excel SKU 导入到 ERPNext 按钮
    listview.page.add_menu_item(__("从Excel导入SKU"), function() {
        open_excel_import_dialog();
    });
};

// 添加行操作按钮
frappe.listview_settings["Item"].button = {
    show: function(doc) {
        return !doc.disabled;
    },
    get_label: function() {
        return __("Sync to WDT");
    },
    get_description: function(doc) {
        return __("Sync Item to WDT");
    },
    action: function(doc) {
        sync_single_item_to_wdt(doc);
    }
};

// 添加库存查询按钮
frappe.listview_settings["Item"].button_inventory = {
    show: function(doc) {
        return !doc.disabled;
    },
    get_label: function() {
        return __("Query Inventory");
    },
    get_description: function(doc) {
        return __("Query item inventory in WDT");
    },
    action: function(doc) {
        query_item_inventory(doc);
    }
};

// 添加库位查询按钮
frappe.listview_settings["Item"].button_position = {
    show: function(doc) {
        return !doc.disabled;
    },
    get_label: function() {
        return __("Query Bin Positions");
    },
    get_description: function(doc) {
        return __("Query bin positions in WDT");
    },
    action: function(doc) {
        query_all_positions();
    }
};

// 同步单个商品到旺店通
function sync_single_item_to_wdt(doc) {
    // 调试信息
    console.log("sync_single_item_to_wdt called with doc:", doc);
    
    // 检查doc和item_code是否存在
    if (!doc) {
        frappe.msgprint(__("Error: Item not found"));
        return;
    }
    
    // 尝试不同的字段名
    let itemCode = doc.item_code || doc.name || doc.id;
    
    if (!itemCode) {
        frappe.msgprint(__("Error: Item Code missing"));
        console.log("Available doc fields:", Object.keys(doc));
        return;
    }
    
    frappe.confirm(
        __("Sync Item '{0}' to WDT?", [itemCode]),
        function() {
            frappe.call({
                method: "upsystem.upsystem.api.sync_item_to_wdt",
                args: {
                    item_code: itemCode
                },
                callback: function(r) {
                    if (r.message && r.message.success) {
                        frappe.show_alert({
                            message: __("Item synced to WDT"),
                            indicator: "green"
                        });
                    } else {
                        let errorMsg = r.message.message || "Unknown error";
                        frappe.msgprint({
                            title: __("Sync Failed"),
                            message: __("Item sync failed: {0}", [errorMsg]),
                            indicator: "red"
                        });
                    }
                },
                error: function(err) {
                    frappe.show_alert({
                        message: __("Sync failed: {0}", [err.message || "Network error"]),
                        indicator: "red"
                    });
                }
            });
        }
    );
}


function open_shopify_import_dialog() {
    const dialog = new frappe.ui.Dialog({
        title: __("从 Shopify 导入商品"),
        fields: [
            {
                fieldtype: "Link",
                label: __("Shopify 店铺"),
                fieldname: "usershop",
                options: "usershop",
                reqd: 1,
            },
            {
                fieldtype: "Link",
                label: __("父目录组"),
                fieldname: "parent_item_group",
                options: "Item Group",
                reqd: 1,
                description: __("新创建的产品分类将在此分组下，没有productType的商品也会放在此分组下"),
                filters: {
                    "is_group": 1
                }
            },
            {
                fieldtype: "Link",
                label: __("默认公司"),
                fieldname: "default_company",
                options: "Company",
                reqd: 1,
                description: __("商品将关联到此公司")
            },
            {
                fieldtype: "Link",
                label: __("默认仓库"),
                fieldname: "default_warehouse",
                options: "Warehouse",
                reqd: 1,
                description: __("商品将关联到此仓库")
            },
            {
                fieldtype: "Link",
                label: __("默认采购商"),
                fieldname: "default_supplier",
                options: "Supplier",
                description: __("商品将关联到此采购商（可选）")
            },
            {
                fieldtype: "Int",
                label: __("批次大小"),
                fieldname: "batch_size",
                default: 50,
                description: __("每次从 Shopify 获取的商品数量")
            },
            {
                fieldtype: "Int",
                label: __("最大分页数"),
                fieldname: "max_pages",
                default: 1,
                description: __("最大处理页数，0表示处理所有页")
            },
            {
                fieldtype: "Data",
                label: __("增量更新时间 (ISO8601)"),
                fieldname: "since",
                description: __("例如 2025-01-01T00:00:00Z，可留空表示获取所有数据"),
            },
        ],
        primary_action_label: __("开始导入"),
        primary_action(values) {
            dialog.hide();
            run_shopify_sync_and_import(values);
        },
    });

    dialog.show();
}

function open_excel_import_dialog() {
    const dialog = new frappe.ui.Dialog({
        title: __("从 Excel 导入 SKU"),
        fields: [
            {
                fieldtype: "Link",
                label: __("Shopify 店铺"),
                fieldname: "usershop",
                options: "usershop",
                description: __("用于获取商品图片，可选"),
            },
            {
                fieldtype: "Link",
                label: __("父目录组"),
                fieldname: "parent_item_group",
                options: "Item Group",
                reqd: 1,
                description: __("新创建的产品分类将在此分组下"),
                filters: {
                    "is_group": 1
                }
            },
            {
                fieldtype: "Link",
                label: __("默认公司"),
                fieldname: "default_company",
                options: "Company",
                reqd: 1,
                description: __("商品将关联到此公司")
            },
            {
                fieldtype: "Link",
                label: __("默认仓库"),
                fieldname: "default_warehouse",
                options: "Warehouse",
                reqd: 1,
                description: __("商品将关联到此仓库")
            },
            {
                fieldtype: "Link",
                label: __("默认采购商"),
                fieldname: "default_supplier",
                options: "Supplier",
                description: __("商品将关联到此采购商（可选）")
            },
        ],
        primary_action_label: __("开始导入"),
        primary_action(values) {
            dialog.hide();
            run_excel_import(values);
        },
    });

    dialog.show();
}

function run_excel_import(values) {
    console.log("[前端调试] 开始执行 run_excel_import", values);
    
    if (!values.parent_item_group) {
        console.log("[前端调试] 错误：未选择父目录组");
        frappe.msgprint(__("请选择父目录组"));
        return;
    }

    if (!values.default_company) {
        console.log("[前端调试] 错误：未选择默认公司");
        frappe.msgprint(__("请选择默认公司"));
        return;
    }

    if (!values.default_warehouse) {
        console.log("[前端调试] 错误：未选择默认仓库");
        frappe.msgprint(__("请选择默认仓库"));
        return;
    }

    const args = {
        parent_item_group: values.parent_item_group,
        default_company: values.default_company,
        default_warehouse: values.default_warehouse,
        default_supplier: values.default_supplier || null,
        shop_name: values.usershop || null
    };
    
    console.log("[前端调试] 调用参数", args);

    frappe.call({
        method: "upsystem.upsystem.api_sku_import_from_excel.import_skus_from_excel_data",
        args: args,
        freeze: true,
        freeze_message: __("正在从Excel数据导入SKU到ERPNext…"),
        callback(res) {
            console.log("[前端调试] 回调响应", res);
            
            if (res.exc) {
                console.log("[前端调试] 响应异常", res.exc);
                frappe.msgprint({
                    title: __("导入失败"),
                    message: res.exc || __("服务器响应异常"),
                    indicator: "red",
                });
                return;
            }

            const result = res.message || {};
            console.log("[前端调试] 解析结果", result);
            
            if (result.success) {
                console.log("[前端调试] 操作成功", result.message);
                frappe.msgprint({
                    title: __("导入完成"),
                    message: result.message || __("操作成功完成"),
                    indicator: "green",
                });
            } else {
                console.log("[前端调试] 操作失败", result.error);
                frappe.msgprint({
                    title: __("导入失败"),
                    message: result.error || __("操作失败"),
                    indicator: "red",
                });
            }
        },
        error(err) {
            console.log("[前端调试] 请求错误", err);
            frappe.msgprint({
                title: __("导入失败"),
                message: err?.message || __("调用接口失败，请稍后重试。"),
                indicator: "red",
            });
        },
    });
}

function run_shopify_import(values) {
    const shopName = values.usershop;
    if (!shopName) {
        frappe.msgprint(__("请选择 Shopify 店铺"));
        return;
    }

    if (!values.parent_item_group) {
        frappe.msgprint(__("请选择父目录组"));
        return;
    }

    frappe.call({
        method: "upsystem.upsystem.api_shop.import_shopify_skus_to_erp",
        args: {
            sku_names: [], // 空数组表示导入所有已同步的SKU
            parent_item_group: values.parent_item_group || "All Item Groups",
            default_company: values.default_company,
            default_warehouse: values.default_warehouse,
            default_supplier: values.default_supplier
        },
        freeze: true,
        freeze_message: __("正在导入Shopify SKU到ERPNext…"),
        callback(res) {
            if (res.exc) {
                return;
            }

            const msg = res.message || {};
            frappe.msgprint({
                title: __("导入完成"),
                message: __(
                    "导入成功：创建 {0} 个，更新 {1} 个",
                    [msg.created || 0, msg.updated || 0]
                ),
                indicator: "green",
            });
        },
        error(err) {
            frappe.msgprint({
                title: __("导入失败"),
                message: err?.message || __("调用接口失败，请稍后重试。"),
                indicator: "red",
            });
        },
    });
}

function run_shopify_sync_and_import(values) {
    console.log("[前端调试] 开始执行 run_shopify_sync_and_import", values);
    
    const shopName = values.usershop;
    if (!shopName) {
        console.log("[前端调试] 错误：未选择 Shopify 店铺");
        frappe.msgprint(__("请选择 Shopify 店铺"));
        return;
    }

    if (!values.parent_item_group) {
        console.log("[前端调试] 错误：未选择父目录组");
        frappe.msgprint(__("请选择父目录组"));
        return;
    }

    if (!values.default_company) {
        console.log("[前端调试] 错误：未选择默认公司");
        frappe.msgprint(__("请选择默认公司"));
        return;
    }

    if (!values.default_warehouse) {
        console.log("[前端调试] 错误：未选择默认仓库");
        frappe.msgprint(__("请选择默认仓库"));
        return;
    }

    const args = {
        shop_name: shopName,
        parent_item_group: values.parent_item_group,
        default_company: values.default_company,
        default_warehouse: values.default_warehouse,
        default_supplier: values.default_supplier,
        batch_size: parseInt(values.batch_size) || 50,
        max_pages: parseInt(values.max_pages) || 1,
        since: values.since || null
    };
    
    console.log("[前端调试] 调用参数", args);

    frappe.call({
        method: "upsystem.upsystem.api_shop.sync_and_import_shopify_skus",
        args: args,
        freeze: true,
        freeze_message: __("正在从Shopify同步并导入SKU到ERPNext…"),
        callback(res) {
            console.log("[前端调试] 回调响应", res);
            
            if (res.exc) {
                console.log("[前端调试] 响应异常", res.exc);
                frappe.msgprint({
                    title: __("同步导入失败"),
                    message: res.exc || __("服务器响应异常"),
                    indicator: "red",
                });
                return;
            }

            const result = res.message || {};
            console.log("[前端调试] 解析结果", result);
            
            if (result.success) {
                console.log("[前端调试] 操作成功", result.message);
                frappe.msgprint({
                    title: __("同步导入完成"),
                    message: result.message || __("操作成功完成"),
                    indicator: "green",
                });
            } else {
                console.log("[前端调试] 操作失败", result.error);
                frappe.msgprint({
                    title: __("同步导入失败"),
                    message: result.error || __("操作失败"),
                    indicator: "red",
                });
            }
        },
        error(err) {
            console.log("[前端调试] 请求错误", err);
            frappe.msgprint({
                title: __("同步导入失败"),
                message: err?.message || __("调用接口失败，请稍后重试。"),
                indicator: "red",
            });
        },
    });
}

// 查询单个商品库存
function query_item_inventory(doc) {
    // 调试信息
    console.log("query_item_inventory called with doc:", doc);
    
    // 检查doc和item_code是否存在
    if (!doc) {
        frappe.msgprint(__("错误：未找到商品信息"));
        return;
    }
    
    // 尝试不同的字段名
    let itemCode = doc.item_code || doc.name || doc.id;
    
    if (!itemCode) {
        frappe.msgprint(__("错误：商品编码不存在"));
        console.log("Available doc fields:", Object.keys(doc));
        return;
    }
    
    frappe.call({
        method: "upsystem.upsystem.api.query_inventory_by_item_code",
        args: {
            item_code: itemCode
        },
        callback: function(r) {
            show_inventory_result_dialog(itemCode, r.message);
        },
        error: function(err) {
            frappe.show_alert({
                message: __("查询失败: {0}", [err.message || "网络错误"]),
                indicator: "red"
            });
        }
    });
}

// 查询所有商品库位
function query_all_positions() {
    frappe.call({
        method: "upsystem.upsystem.api.query_position_by_item_code",
        args: {},
        callback: function(r) {
            show_position_result_dialog(r.message);
        },
        error: function(err) {
            frappe.show_alert({
                message: __("查询失败: {0}", [err.message || "网络错误"]),
                indicator: "red"
            });
        }
    });
}

// 批量查询商品库存
function query_items_inventory(listview) {
    // 调试信息
    console.log("query_items_inventory called with listview:", listview);
    
    // 获取选中的商品
    let selected_items = [];
    
    // 方法1：尝试使用get_checked_items()
    if (typeof listview.get_checked_items === 'function') {
        selected_items = listview.get_checked_items();
        console.log("get_checked_items()返回:", selected_items);
    }
    
    // 方法2：如果上面方法返回的不是数组或为空，尝试其他方法
    if (!Array.isArray(selected_items) || selected_items.length === 0) {
        console.log("尝试其他方法获取选中商品");
        
        // 从DOM获取选中的行
        let checked_rows = listview.wrapper.find('input[type="checkbox"]:checked');
        console.log("找到选中的复选框数量:", checked_rows.length);
        
        checked_rows.each(function() {
            let checkbox = $(this);
            let row = checkbox.closest('tr, .list-row');
            
            // 获取商品编码 - 尝试多种方式
            let item_code = row.find('[data-fieldname="item_code"]').text().trim() ||
                           row.find('.list-row-col[data-fieldname="item_code"]').text().trim() ||
                           row.attr('data-name') ||
                           row.find('a[data-name]').attr('data-name') ||
                           row.find('.list-row-col:first').text().trim();
            
            if (item_code && item_code.length > 1) { // 确保不是单个字符
                selected_items.push({item_code: item_code});
                console.log("找到商品编码:", item_code);
            }
        });
    }
    
    console.log("最终选中的商品:", selected_items);
    
    if (selected_items.length === 0) {
        frappe.msgprint(__("请先选择要查询库存的商品"));
        return;
    }

    frappe.confirm(
        __("确定要查询选中的 {0} 个商品的库存吗？", [selected_items.length]),
        function() {
            // 确保获取正确的item_code
            let item_codes = selected_items.map(item => {
                let code = item.item_code || item.name || item;
                console.log("处理商品:", item, "-> 编码:", code);
                return code;
            }).filter(code => code && code.length > 1); // 过滤掉无效的编码
            
            console.log("准备查询库存的商品编码:", item_codes);
            
            let all_inventory_data = [];
            let completed_count = 0;
            
            item_codes.forEach(function(item_code, index) {
                frappe.call({
                    method: "upsystem.upsystem.api.query_inventory_by_item_code",
                    args: {
                        item_code: item_code
                    },
                    callback: function(r) {
                        completed_count++;
                        
                        if (r.message && r.message.success) {
                            all_inventory_data.push({
                                item_code: item_code,
                                success: true,
                                data: r.message.data
                            });
                        } else {
                            all_inventory_data.push({
                                item_code: item_code,
                                success: false,
                                error: r.message.message || "查询失败"
                            });
                        }
                        
                        if (completed_count === item_codes.length) {
                            show_batch_inventory_result_dialog({
                                success: true,
                                data: {
                                    success_count: all_inventory_data.filter(item => item.success).length,
                                    fail_count: all_inventory_data.filter(item => !item.success).length,
                                    results: all_inventory_data
                                }
                            });
                        }
                    },
                    error: function(err) {
                        completed_count++;
                        all_inventory_data.push({
                            item_code: item_code,
                            success: false,
                            error: err.message || "网络错误"
                        });
                        
                        if (completed_count === item_codes.length) {
                            show_batch_inventory_result_dialog({
                                success: true,
                                data: {
                                    success_count: all_inventory_data.filter(item => item.success).length,
                                    fail_count: all_inventory_data.filter(item => !item.success).length,
                                    results: all_inventory_data
                                }
                            });
                        }
                    }
                });
            });
        }
    );
}

// 批量查询商品库存（WDT + Shopify）
function query_items_inventory_with_shopify(listview) {
    console.log("query_items_inventory_with_shopify called with listview:", listview);

    // 先获取选中的商品（与 query_items_inventory 基本一致，但保留 item_name）
    let selected_items = [];

    if (typeof listview.get_checked_items === "function") {
        selected_items = listview.get_checked_items();
        console.log("get_checked_items() 返回:", selected_items);
    }

    if (!Array.isArray(selected_items) || selected_items.length === 0) {
        console.log("尝试其他方法获取选中商品");

        let checked_rows = listview.wrapper.find('input[type="checkbox"]:checked');
        console.log("找到选中的复选框数量:", checked_rows.length);

        checked_rows.each(function () {
            let checkbox = $(this);
            let row = checkbox.closest("tr, .list-row");

            let item_code =
                row.find('[data-fieldname="item_code"]').text().trim() ||
                row.find('.list-row-col[data-fieldname="item_code"]').text().trim() ||
                row.attr("data-name") ||
                row.find("a[data-name]").attr("data-name") ||
                row.find(".list-row-col:first").text().trim();

            let item_name =
                row.find('[data-fieldname="item_name"]').text().trim() ||
                row.find('.list-row-col[data-fieldname="item_name"]').text().trim() ||
                item_code;

            if (item_code && item_code.length > 1) {
                selected_items.push({ item_code: item_code, item_name: item_name });
                console.log("找到商品编码:", item_code, "名称:", item_name);
            }
        });
    }

    console.log("最终选中的商品:", selected_items);

    if (selected_items.length === 0) {
        frappe.msgprint(__("请先选择要查询库存的商品"));
        return;
    }

    // 先让用户选择 Shopify 店铺（usershop）
    const dialog = new frappe.ui.Dialog({
        title: __("选择 Shopify 店铺并查询库存"),
        fields: [
            {
                fieldtype: "Link",
                label: __("Shopify 店铺"),
                fieldname: "usershop",
                options: "usershop",
                reqd: 1,
            },
        ],
        primary_action_label: __("开始查询"),
        primary_action(values) {
            if (!values.usershop) {
                frappe.msgprint(__("请选择 Shopify 店铺"));
                return;
            }

            dialog.hide();

            // 组装后端需要的 items 列表：{ sku, sku_name }
            let items_payload = selected_items
                .map((item) => {
                    const sku = item.item_code || item.name || item;
                    const name = item.item_name || item.item_code || item.name || sku;
                    return {
                        sku: sku,
                        sku_name: name,
                    };
                })
                .filter((it) => it.sku && it.sku.length > 1);

            console.log("准备查询的 items:", items_payload);

            frappe.call({
                method: "upsystem.upsystem.api_wdt_stock.get_wdt_and_shopify_stock",
                args: {
                    shopname: values.usershop,
                    items: items_payload,
                },
                freeze: true,
                freeze_message: __("正在查询 WDT 与 Shopify 库存…"),
                callback: function (r) {
                    console.log("get_wdt_and_shopify_stock 返回:", r);
                    if (!r.message || !r.message.success) {
                        frappe.msgprint({
                            title: __("查询失败"),
                            message:
                                (r.message && r.message.message) ||
                                __("接口调用失败，请检查后台日志"),
                            indicator: "red",
                        });
                        return;
                    }

                    // 直接复用批量结果弹框，查看 JSON 结果
                    show_batch_inventory_result_dialog(r.message);
                },
                error: function (err) {
                    frappe.show_alert({
                        message: __("查询失败: {0}", [err.message || "网络错误"]),
                        indicator: "red",
                    });
                },
            });
        },
    });

    dialog.show();
}
//gid://shopify/InventoryItem/45409540636774
// 显示库存查询结果弹框
function show_inventory_result_dialog(itemCode, result) {
    let d = new frappe.ui.Dialog({
        title: __("库存查询结果 - {0}", [itemCode]),
        fields: [
            {
                "fieldtype": "Small Text",
                "fieldname": "result_json",
                "label": __("旺店通返回结果"),
                "default": JSON.stringify(result, null, 2),
                "read_only": 1
            }
        ],
        size: "large"
    });
    
    d.show();
}

// 显示批量库存查询结果弹框
function show_batch_inventory_result_dialog(result) {
    let d = new frappe.ui.Dialog({
        title: __("批量库存查询结果"),
        fields: [
            {
                "fieldtype": "Small Text",
                "fieldname": "result_json",
                "label": __("旺店通返回结果"),
                "default": JSON.stringify(result, null, 2),
                "read_only": 1
            }
        ],
        size: "large"
    });
    
    d.show();
}

// 显示库位查询结果弹框
function show_position_result_dialog(result) {
    let d = new frappe.ui.Dialog({
        title: __("库位查询结果"),
        fields: [
            {
                "fieldtype": "Small Text",
                "fieldname": "result_json",
                "label": __("旺店通返回结果"),
                "default": JSON.stringify(result, null, 2),
                "read_only": 1
            }
        ],
        size: "large"
    });
    
    d.show();
}

// 批量同步商品到旺店通
function sync_items_to_wdt(listview) {
    // 调试信息
    console.log("sync_items_to_wdt called with listview:", listview);
    
    // 获取选中的商品 - 使用正确的方法
    let selected_items = [];
    
    // 方法1：尝试使用get_checked_items()
    if (typeof listview.get_checked_items === 'function') {
        selected_items = listview.get_checked_items();
        console.log("get_checked_items()返回:", selected_items);
    }
    
    // 方法2：如果上面方法返回的不是数组或为空，尝试其他方法
    if (!Array.isArray(selected_items) || selected_items.length === 0) {
        console.log("尝试其他方法获取选中商品");
        
        // 从DOM获取选中的行
        let checked_rows = listview.wrapper.find('input[type="checkbox"]:checked');
        console.log("找到选中的复选框数量:", checked_rows.length);
        
        checked_rows.each(function() {
            let checkbox = $(this);
            let row = checkbox.closest('tr, .list-row');
            
            // 获取商品编码 - 尝试多种方式
            let item_code = row.find('[data-fieldname="item_code"]').text().trim() ||
                           row.find('.list-row-col[data-fieldname="item_code"]').text().trim() ||
                           row.attr('data-name') ||
                           row.find('a[data-name]').attr('data-name') ||
                           row.find('.list-row-col:first').text().trim();
            
            if (item_code && item_code.length > 1) { // 确保不是单个字符
                selected_items.push({item_code: item_code});
                console.log("找到商品编码:", item_code);
            }
        });
    }
    
    console.log("最终选中的商品:", selected_items);
    
    if (selected_items.length === 0) {
        frappe.msgprint(__("请先选择要同步的商品"));
        return;
    }

    frappe.confirm(
        __("确定要将选中的 {0} 个商品同步到旺店通吗？", [selected_items.length]),
        function() {
            // 确保获取正确的item_code
            let item_codes = selected_items.map(item => {
                let code = item.item_code || item.name || item;
                console.log("处理商品:", item, "-> 编码:", code);
                return code;
            }).filter(code => code && code.length > 1); // 过滤掉无效的编码
            
            console.log("准备同步的商品编码:", item_codes);
            
            frappe.call({
                method: "upsystem.upsystem.api.batch_sync_items_to_wdt",
                args: {
                    item_codes: item_codes
                },
                callback: function(r) {
                    if (r.message && r.message.success) {
                        let success_count = r.message.data.success_count || 0;
                        let fail_count = r.message.data.fail_count || 0;
                        let results = r.message.data.results || [];
                        
                        if (fail_count === 0) {
                            frappe.show_alert({
                                message: __("所有商品同步成功！共 {0} 个", [success_count]),
                                indicator: "green"
                            });
                        } else {
                            // 显示详细的失败信息
                            let fail_items = results.filter(r => !r.success).map(r => r.item_code).join(', ');
                            frappe.msgprint({
                                title: __("同步完成"),
                                message: __("成功: {0} 个，失败: {1} 个<br/>失败商品: {2}", 
                                    [success_count, fail_count, fail_items]),
                                indicator: "orange"
                            });
                        }
                        
                        // 刷新列表
                        listview.refresh();
                    } else {
                        frappe.msgprint({
                            title: __("同步失败"),
                            message: __("批量同步失败: {0}", [r.message.message || "未知错误"]),
                            indicator: "red"
                        });
                    }
                },
                error: function(err) {
                    frappe.show_alert({
                        message: __("批量同步失败: {0}", [err.message || "网络错误"]),
                        indicator: "red"
                    });
                }
            });
        }
    );
}